package com.shuang.service.impl;

import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.shuang.common.util.DataUtil;
import com.shuang.common.util.StringUtil;
import com.shuang.mapper.SsoLocalUserMapper;
import com.shuang.pojo.SsoLocalUser;
import com.shuang.pojo.SsoLocalUserExample;
import com.shuang.pojo.SsoLocalUserExample.Criteria;
import com.shuang.service.IDService;
@Service("iDService")
public class IDServiceImpl implements IDService {

	@Resource(name="ssoLocalUserMapper")
	private SsoLocalUserMapper ssoLocalUserMapper;
	
	@Override
	public synchronized String getNewSsoLocalUserName() {
		SsoLocalUserExample example = new SsoLocalUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andStatusEqualTo("0");//获取没有被注册的
		List<SsoLocalUser> result = ssoLocalUserMapper.selectByExample(example);
		if(result==null||result.size()==0){//数据表里面没有可以注册的username
			IncrementUserNameToSsoLocalUser();
			result = ssoLocalUserMapper.selectByExample(example);
		}
		SsoLocalUser record=result.get(0);
		record.setStatus("1");//获取到了就设置状态为被注册
		ssoLocalUserMapper.updateByPrimaryKey(record);
		
		return record.getUsername();
	}
	/**
	 * 自增可注册账号
	 */
	private void IncrementUserNameToSsoLocalUser() {
		//TODO 写一个方法自动添加唯一账号
		String dateStr=DataUtil.getFormatDate("yyyyMMdd");
		List<SsoLocalUser> result=ssoLocalUserMapper.selectByYear(dateStr);
		if(result != null && result.size()>0){//当前已经有初始化账号了就获取最大的账号
			String maxnum = result.get(0).getUsername().substring(dateStr.length());
			if(StringUtil.notNull(maxnum)){
				int size = Integer.parseInt(maxnum);
				addTempLocalUser(dateStr,size);
			}
		}else{ //从0001开始增加
			addTempLocalUser(dateStr,0);
		}
	}
	//添加可注册账号封装
	private void addTempLocalUser(String dateStr,int size){
		SsoLocalUser ssoLocalUser=new SsoLocalUser();
		for(int i=size+1;i<size+100;i++){
			if(i < 10){
				dateStr=dateStr+"000"+i;
			}else if(i>9 && i<100){
				dateStr=dateStr+"00"+i;
			}else if(i>99 && i<1000){
				dateStr=dateStr+"0"+i;
			}else{
				dateStr=dateStr+i;
			}
			ssoLocalUser.setId(UUID.randomUUID().toString());
			ssoLocalUser.setUsername(dateStr);
			ssoLocalUser.setAddtime(DataUtil.getDate());
			ssoLocalUser.setStatus("0");
			ssoLocalUserMapper.insertSelective(ssoLocalUser);
		}
	}
}	
